package com.thirtywords.cleaner;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;

import com.thirtywords.analizer.beans.Link;

public class PageCleaner extends CleanerRunnable {

	public PageCleaner(String url, int deep) {
		super(url, deep);
	}

	@Override
	public void run() {

		if (code!=null && code.getUrl() != null) {

			HashSet<String> invalidElements = new HashSet<String>();
			invalidElements.add(HTMLElementName.ACRONYM);
			invalidElements.add(HTMLElementName.SUB);
			invalidElements.add(HTMLElementName.SUP);
			invalidElements.add(HTMLElementName.IMG);
			invalidElements.add(HTMLElementName.TITLE);
			invalidElements.add(HTMLElementName.FORM);
			invalidElements.add(HTMLElementName.SCRIPT);
			invalidElements.add(HTMLElementName.ASIDE);

			try {
//				System.out.println(this.deep+">>" + code.getUrl());

				StringBuilder builder = new StringBuilder();
				List<Element> elements = getElements(code);
				List<Link> links = new ArrayList<Link>();

				for (Element element : elements) {

					if (!invalidElements.contains(element.getName())) {

						String content = element.getContent()
								.getTextExtractor().toString().trim();

						if (element.getName().equals(HTMLElementName.A)) {

							Link link = new Link();
							link.setHref(element.getAttributeValue("href"));
							link.setText(content);

//							System.out.println(this.deep+">>>>" + content);
							links.add(link);
						}

						builder.append("<p>" + content + "</p>");

					}
				}

				if (this.deep < Cleaner.MAX_DEEP) {

					System.out.print(this.deep);
					System.out.print("Cleaner.MAX_DEEP"+Cleaner.MAX_DEEP);
					System.out.println(" entrou");
					getNextLevel(links);
				}

			} catch (Exception e) {
				//e.printStackTrace();
			}
		}
	}
	
	@Override
	public String doClean() {
		// TODO Auto-generated method stub
		return null;
	}
}
